22E - Scheme - CodeForces Solution


dfs and similar graphs trees *2300

Please click on ads to support us..

Python Code:


N=int(input())
A=list(map(int,input().split()))

E=[[] for i in range(N)]
E_INV=[[] for i in range(N)]

for i in range(N):
    x,y=i,A[i]-1
    E[x].append(y)
    E_INV[y].append(x)

def Top_sort(E):
    Parent=[-1]*N
    USEIND=[0]*N
    TOP=[]

    for ROOT in range(N):
        if Parent[ROOT]!=-1:
            continue
        Parent[ROOT]=ROOT

        NOW=ROOT

        while NOW!=ROOT or USEIND[ROOT]!=len(E[ROOT]):

            if USEIND[NOW]==len(E[NOW]):
                TOP.append(NOW)
                NOW=Parent[NOW]
            elif E[NOW][USEIND[NOW]]==Parent[NOW]:
                USEIND[NOW]+=1
            else:
                NEXT=E[NOW][USEIND[NOW]]
                USEIND[NOW]+=1
                if Parent[NEXT]==-1:
                    Parent[NEXT]=NOW
                    NOW=NEXT
        TOP.append(ROOT)
        
    return TOP[::-1]


USE=[0]*N
SCC=[]

def dfs2(x):
    Q=[x]
    USE[x]=1
    ANS=[]

    while Q:
        x=Q.pop()
        ANS.append(x)
        for to in E_INV[x]:
            if USE[to]==0:
                USE[to]=1
                Q.append(to)
    return ANS

TOP_SORT=Top_sort(E)

for x in TOP_SORT:
    if USE[x]==0:
        SCC.append(dfs2(x))


Group = [i for i in range(N+1)] Nodes = [1]*(N+1) 
def find(x):
    while Group[x] != x:
        x=Group[x]
    return x

def Union(x,y):
    if find(x) != find(y):
        if Nodes[find(x)] < Nodes[find(y)]:
            
            Nodes[find(y)] += Nodes[find(x)]
            Nodes[find(x)] = 0
            Group[find(x)] = find(y)
            
        else:
            Nodes[find(x)] += Nodes[find(y)]
            Nodes[find(y)] = 0
            Group[find(y)] = find(x)

for i in range(N):
    Union(i+1,A[i])

LAST=[]
USE=[0]*(N+1)
for scc in SCC[::-1]:
    for x in scc[::-1]:
        if USE[find(x+1)]==0:
            USE[find(x+1)]=1
            LAST.append(x+1)

FIRST=[]
USE=[0]*(N+1)
for scc in SCC:
    for x in scc:
        if USE[find(x+1)]==0:
            USE[find(x+1)]=1
            FIRST.append(x+1)

USE=[0]*(N+1)
for a in A:
    USE[a]=1

ANS=[]
ind=1

FIRST.sort(key=lambda x:find(x))
LAST.sort(key=lambda x:find(x))

if len(LAST)!=1:
    for i in FIRST:
        if ind==len(LAST):
            ind=0
        ANS.append((LAST[ind],i))
        Union(LAST[ind],i)
        USE[i]+=1
        USE[LAST[ind]]+=1

        ind+=1
if ind==len(LAST):
    ind=0

    
for i in range(1,N+1):
    if USE[i]==0:
        while Nodes[find(i)]<N and find(i)==find(LAST[ind]):
            ind+=1
            if ind==len(LAST):
                ind=0
                
        ANS.append((LAST[ind],i))
        Union(LAST[ind],i)




print(len(ANS))
for x,y in ANS:
    print(x,y)
    


Comments

Submit
0 Comments
More Questions

120. Triangle
102. Binary Tree Level Order Traversal
96. Unique Binary Search Trees
75. Sort Colors
74. Search a 2D Matrix
71. Simplify Path
62. Unique Paths
50. Pow(x, n)
43. Multiply Strings
34. Find First and Last Position of Element in Sorted Array
33. Search in Rotated Sorted Array
17. Letter Combinations of a Phone Number
5. Longest Palindromic Substring
3. Longest Substring Without Repeating Characters
1312. Minimum Insertion Steps to Make a String Palindrome
1092. Shortest Common Supersequence
1044. Longest Duplicate Substring
1032. Stream of Characters
987. Vertical Order Traversal of a Binary Tree
952. Largest Component Size by Common Factor
212. Word Search II
174. Dungeon Game
127. Word Ladder
123. Best Time to Buy and Sell Stock III
85. Maximal Rectangle
84. Largest Rectangle in Histogram
60. Permutation Sequence
42. Trapping Rain Water
32. Longest Valid Parentheses
Cutting a material